Query Batching - Problem
Design and implement a QueryBatcher class that efficiently batches multiple small queries into larger ones using a throttling mechanism.
The class constructor accepts:
queryMultiple: An asynchronous function that takes an array of string keys and returns a Promise resolving to an array of corresponding valuest: Throttle time in milliseconds
Implement the method:
async getValue(key): Returns a Promise that resolves to the value for the given key
Throttling Rules:
- First call to
getValueimmediately triggersqueryMultiple - Subsequent calls within
tmilliseconds are batched together - After
tmilliseconds, all pending keys are sent toqueryMultiple - Each key is guaranteed to be unique
Input & Output
Example 1 — Basic Throttling
$
Input:
queryMultiple = async (keys) => keys.map(k => `value_${k}`), t = 100
›
Output:
First getValue('key1') returns 'value_key1' immediately, subsequent calls batched
💡 Note:
First call executes immediately. Calls within 100ms window get batched together and executed after timeout.
Example 2 — Multiple Batches
$
Input:
Multiple getValue calls over time with 200ms throttle
›
Output:
Separate batches for calls outside throttle window
💡 Note:
Calls separated by more than throttle time create new batches, maintaining efficient grouping.
Example 3 — Single Key Immediate
$
Input:
Single getValue call when no pending queries
›
Output:
Immediate execution without waiting
💡 Note:
When no queries are pending and enough time has passed, execute immediately for best performance.
Constraints
- 1 ≤ t ≤ 104 (throttle time in milliseconds)
- queryMultiple never rejects
- All keys passed to getValue are unique
- queryMultiple returns array same length as input
Visualization
Tap to expand
Understanding the Visualization
1
Input Queries
Multiple getValue calls with different keys
2
Throttle Logic
First call immediate, others batched within time window
3
Batched Output
Fewer queryMultiple calls with better efficiency
Key Takeaway
🎯 Key Insight: Throttling creates optimal batches while maintaining fast response for the first query
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code