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 values
  • t: 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 getValue immediately triggers queryMultiple
  • Subsequent calls within t milliseconds are batched together
  • After t milliseconds, all pending keys are sent to queryMultiple
  • 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
Query Batching System: Reducing Network OverheadIndividual QueriesgetValue('key1')getValue('key2')getValue('key3')QueryBatcherThrottle: 100msBatching LogicqueryMultiple(['key1'])ImmediatequeryMultiple(['key2','key3'])Batched after 100msEfficiency Gain: 3 queries → 2 network calls (33% reduction)Smart throttling balances responsiveness with batching benefits
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
Asked in
Netflix 15 Uber 12 Meta 10 Google 8
25.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen