API Request Lifecycle
Relevant source files
The following files were used as context for generating this wiki page:The API request lifecycle in Read Frog is a managed system designed to handle external API calls for translation and AI-powered content analysis. It prioritizes efficiency, reliability, and cost-effectiveness by implementing rate limiting, request batching, deduplication, and automatic retries. The system is primarily orchestrated within the extension's background service worker.
Two main request lifecycles exist: one for page translation, which uses a sophisticated background queuing system, and another for the "Read Article" feature, which handles requests more directly from the content script. This document details the architecture and flow of these systems.
Core Components
The request management system is built upon two primary classes: RequestQueue and BatchQueue.
RequestQueue
This is the foundational component for managing and throttling outgoing API requests. It uses a token-bucket algorithm to control the rate of execution, ensuring that the application does not exceed API rate limits.
Sources: src/utils/request/request-queue.ts
The diagram below illustrates the structure of the RequestQueue class.
Key Features
- Rate Limiting: Implements a token-bucket algorithm.
capacitydefines the burst limit, andratedefines the number of requests allowed per second on average. - Deduplication: If multiple requests with the same
hashare enqueued, only the first one is executed. Subsequent requests receive the promise of the original task. - Retries: Automatically retries failed requests up to
maxRetriestimes with exponential backoff, starting withbaseRetryDelayMs. - Timeouts: A request will fail if it does not complete within
timeoutMs. - Dynamic Configuration: The queue's
rateandcapacitycan be updated at runtime via thesetQueueOptionsmethod, which is triggered by thesetTranslateRequestQueueConfigmessage.
Sources: src/utils/request/request-queue.ts:100-111, src/utils/request/request-queue.ts:153-178, src/utils/request/request-queue.ts:223-231, src/entrypoints/background/translation-queues.ts:199-202
BatchQueue
Built on top of RequestQueue, the BatchQueue is designed to reduce API costs and improve efficiency by bundling multiple small requests into a single, larger batch request. This is particularly effective for LLM-based translations.
Sources: src/utils/request/batch-queue.ts
The diagram below shows the structure of the BatchQueue class.
Key Features
- Automatic Batching: Collects individual requests and groups them based on a
batchKey(e.g., source/target language pair). - Configurable Limits: Batches are created when
maxItemsPerBatch,maxCharactersPerBatch, orbatchDelayis reached. - Fallback Mechanism: If a batch request fails, it can automatically fall back to sending each item as an individual request, ensuring reliability.
- Cost Tracking: Records the number of original requests and batch requests to provide statistics on cost savings.
Sources: src/utils/request/batch-queue.ts:20-42, src/utils/request/batch-queue.ts:109-110, src/entrypoints/background/translation-queues.ts:110-114
Translation Request Flow
Page translation requests are handled by the background script, leveraging the full queuing system for optimal performance and cost management.
The following sequence diagram illustrates the lifecycle of a translation request.
Flow Steps
- Initiation: A component requests a translation, triggering the
enqueueTranslateRequestmessage to the background script. - Cache Check: The background script first checks
Dexie(db.translationCache) for a cached result using the request's hash. If found, it's returned immediately. - Provider Check: If not cached, the system checks if the configured translation provider is an LLM.
- Queuing:
- LLM Providers: The request is sent to the
BatchQueue. It will be held and grouped with other compatible requests before being executed as a single batch. - Non-LLM Providers: The request is sent directly to the
RequestQueuefor individual execution, subject to rate limiting.
- LLM Providers: The request is sent to the
- Execution: The
RequestQueueexecutes the task (either a single request or a batch) by callingexecuteTranslate. - Caching: Upon successful completion, the translation result is stored in the
translationCachefor future use. - Return: The result is sent back to the original requester.
Sources: src/entrypoints/background/translation-queues.ts:165-197
"Read Article" Request Flow
The "Read Article" feature, which includes content analysis and explanation, follows a different, more direct lifecycle managed by React hooks in the side panel content script. It does not use the background RequestQueue or BatchQueue.
This flow is managed by the useReadArticle, useAnalyzeContent, and useExplainArticle hooks.
Sources: src/hooks/read/read.tsx:210-251
The diagram below shows the high-level flow for analyzing and explaining an article.
Sources: src/hooks/read/read.tsx
- Analysis: The
useAnalyzeContenthook makes a single API call via the Vercel AI SDK'sgenerateObjectfunction to get an initial analysis of the article. - Explanation Batching: The
useExplainArticlehook splits the article's paragraphs into smaller batches based on character count (MAX_CHARACTERS = 1000). - Sequential Execution: It then uses a helper function,
sendInBatchesWithFixedDelay, to process these batches sequentially. For each batch, it callsexplainBatch, which in turn callsgenerateObjectto get a detailed explanation from the AI provider. - Retries: Each
explainBatchcall has its own internal retry logic (MAX_ATTEMPTS = 3).
This client-side batching is simpler than the background queue system and is designed to process a single article's content chunk by chunk, rather than managing concurrent requests from across the extension.
Sources: src/hooks/read/read.tsx:32-79, src/hooks/read/read.tsx:129-183
Configuration
The behavior of the translation queuing system is highly configurable through the extension's options page.
Sources: src/locales/en.yml:132-151
Request Queue Configuration (requestQueueConfig)
| Parameter | Description | Default Value |
|---|---|---|
capacity | The maximum number of requests that can be processed concurrently in a short burst. | 300 |
rate | The average number of requests allowed per second. | 5 |
Sources: src/locales/en.yml:137-142, src/entrypoints/background/translation-queues.ts:19-20
Batch Queue Configuration (batchQueueConfig)
| Parameter | Description | Default Value |
|---|---|---|
maxCharactersPerBatch | Maximum number of characters allowed per batch request. | (from config) |
maxItemsPerBatch | Maximum number of paragraphs for each batch translation. | (from config) |
Sources: src/locales/en.yml:146-151, src/entrypoints/background/translation-queues.ts:20-21
These settings are initialized in setUpRequestQueue and can be dynamically updated by sending setTranslateRequestQueueConfig or setTranslateBatchQueueConfig messages from the options page.
Sources: src/entrypoints/background/translation-queues.ts:199-206
Summary
Read Frog employs two distinct API request lifecycles to serve its features. For widespread translation tasks, it uses a robust background queuing system with RequestQueue and BatchQueue to manage rate limits, reduce costs, and ensure reliability. For the more specialized "Read Article" feature, it uses a simpler, client-side batching approach within React hooks. This separation of concerns allows each system to be optimized for its specific use case, providing a responsive and efficient user experience.